<template>
	<div>
		<!-- 面包屑导航区域 -->
	    <el-breadcrumb separator-class="el-icon-arrow-right">
	      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
	      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
	      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
	    </el-breadcrumb>
	    <!--角色卡片试图-->
	    <el-card class="box-card">
	    <!-- 添加角色按钮区域 -->
		   <el-row>
		   	  <el-col>
		   	  	<el-button type="primary">添加角色</el-button>
		   	  </el-col>
		   </el-row>
		<!--角色列表-->
		  <template>
		    <el-table
		      :data="rolesList"
		      style="width: 100%"
          >
		      <!--展开列-->
		      <el-table-column type="expand">
		      	<template slot-scope="scope">
		      	  <el-row  v-for="(item,i1) in scope.row.children" :key="item.id" :class="['bdbottom', i1 === 0 ? 'bdtop' : '']">
		      		<!--第一层级-->
		      		<el-col :span="5">
		      		  <el-tag closable @close="removeRightById(scope.row,item.id)">{{ item.authName }}</el-tag>
		      		</el-col>
		      		<!--第二层级，第三层级-->
		      		<el-col :span="19">
		      			<!--渲染第二层级-->
		      			<el-row v-for="(item2, i2) in item.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bdtop']">
		      			  <el-col :span="6">
		      			  	<el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{ item2.authName }}</el-tag>
		      			  </el-col>
                          <!--渲染第三层级-->
			      		  <el-col :span="18">
	                        <el-tag type="warning" closable @close="removeRightById(scope.row,item3.id)" v-for="item3 in item2.children" :key="item3.id">{{ item3.authName }}</el-tag>
			      		  </el-col>
		      			</el-row>
		      		</el-col>
		      	  </el-row>	
		      	</template>
		      </el-table-column>

		      <!--索引列-->
		      <el-table-column type="index"></el-table-column>
		      <el-table-column label="角色名称" prop="roleName"></el-table-column>
              <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
              <el-table-column label="操作" width="300px">
              	<template slot-scope="scope">
              	  <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
	              <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
	              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>	
              	</template>
              </el-table-column>
		    </el-table>
		  </template>   
		</el-card>
		<!-- 分配权限的对话框 -->
		<el-dialog
		  title="角色权限分配"
		  :visible.sync="setRightDialogVisible"
		  width="50%" @close="setRightDialogClosed">
		  <el-tree :data="rightList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defaultCheckedKey" ref="treeRef"></el-tree>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRightDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="allotRight">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>
<script>
export default {
  data () {
  	return {
  		rolesList: [],
  		// 控制角色权限分配对话框开关
        setRightDialogVisible: false,
        rightList: [],
        treeProps: {
        	label: 'authName',
        	children: 'children'
        },
        defaultCheckedKey: [],
        rolesId:0
  	}
  },
  created () {
  	this.getRoleList()
  },
  methods: {
    async getRoleList () {
    	const { data: res } = await this.$http.get('roles')
    	if (res.meta.status !== 200) {
    		return this.$message.error('获取角色列表失败')
    	}
      console.log(res)
    	this.rolesList = res.data
    },
    async showSetRightDialog (role) {
    	// 展示角色权限对话框
    	this.setRightDialogVisible = true
    	// 以树形获取所有权限列表
    	const { data: res } = await this.$http.get('rights/tree')
    	if (res.meta.status !== 200 ) {
    		return this.$message.error('获取权限数据失败')
    	}
    	this.rightList = res.data
    	// 展示默认选中的权限 递归获取节点id
    	this.getLeafKeys(role, this.defaultCheckedKey)
        this.rolesId = role.id
    },
    getLeafKeys (node, arr) {
    	// 如果传入的node下面没有children节点 则表明是最后一组 将id保存到数组中
    	if (!node.children) {
    		return arr.push(node.id)
    	}
    	// 否则遍历children节点 调用自身
    	node.children.forEach(item => {
    		this.getLeafKeys(item,arr)
    	})
    },
    setRightDialogClosed () {
    	this.defaultCheckedKey = []
    },
    // 为角色添加权限
    async allotRight () {
      // 获得当前角色所有被选中的权限id，包括半选状态的节点id
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      const keyStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: keyStr })
      if (res.meta.status !== 200) {
      	return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible=false
    },
    //删除权限
    async removeRightById (role,Id) {
    	const confirmResult = await this.$msgbox.confirm('此操作将永久删除该权限, 是否继续?', '提示',{
    	  confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
    	}).catch(err=>err)
    	if (confirmResult !== 'confirm') {
    		 return this.$message.info('取消了删除！')
    	}
    	const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${Id}`)
    	if (res.meta.status !== 200) {
	         return this.$message.error('删除权限失败！')
	    }
	    role.children = res.data
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>